package com.zhuguowei.chapter_2_4.socket;

import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.zhuguowei.chapter_2_4.R;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;

public class TcpClientActivity extends AppCompatActivity {

    private static final String TAG = "TcpClientActivity";
    private static final int MESSAGE_RECEIVE_NEW_MSG = 1;
    private static final int MESSAGE_SOCKET_CONNECTED = 2;

    private Socket mClientSocket;
    private PrintWriter mPrintWriter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tcp_client);
        //开启线程连接服务端 zgw-2017/12/5 16:42
        new Thread(){
            @Override
            public void run() {
                Socket socket = null;
                while (socket == null) {
                    try {
                        socket = new Socket("localhost",8688);
                        mClientSocket = socket;
                        mPrintWriter = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
                        Log.e(TAG, "connect server success.");
                    } catch (IOException e) {
                        SystemClock.sleep(1000);
                        Log.e(TAG, "connect tcp server failed,retry...");
                    }
                }
            }
        }.start();
    }
}
